package com.wt.struggle.goodbye.wxapi;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.wt.struggle.goodbye.base.Share;
import com.wt.struggle.goodbye.info.ProUserInfo;
import com.wt.struggle.goodbye.wxutil.Contact;
import com.xin.lv.yang.utils.net.BaseHandler;
import com.xin.lv.yang.utils.utils.HttpUtils;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 微信登录相关回调
 */

public class WXEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {

    private IWXAPI api;
    Handler handler;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        api = WXAPIFactory.createWXAPI(this, Contact.WEIXIN_ID, true);
        api.handleIntent(getIntent(), this);
        handler = new MyHandler(WXEntryActivity.this);

    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);

    }

    String openId;
    String accessToken;
    String refreshToken;


    private static class MyHandler extends BaseHandler<WXEntryActivity> {

        private MyHandler(WXEntryActivity o) {
            super(o);
        }

        WXEntryActivity w = weak.get();

        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            String str = (String) msg.obj;

            Log.i("result", "返回=====" + str);

            switch (msg.what) {
                case 111:
                    try {
                        JSONObject object = new JSONObject(str);
                        w.accessToken = object.getString("access_token");
                        w.openId = object.getString("openid");
                        w.refreshToken = object.getString("refresh_token");
                        long expires_in = object.getLong("expires_in");

                        w.getUserInfo(w.accessToken, w.openId);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                case 123:

                    ProUserInfo proUserInfo = new Gson().fromJson(str, ProUserInfo.class);
                    if (onBackText != null) {
                        onBackText.get(0, proUserInfo);
                        w.finish();
                    }

                    break;

            }

        }
    }


    static OnBackText onBackText;
    static OnShareCallBack onShareCallBack;

    public static void setOnShareCallBack(OnShareCallBack onShareCallBack) {
        WXEntryActivity.onShareCallBack = onShareCallBack;
    }

    public OnBackText getOnBackText() {
        return onBackText;
    }

    public static void setOnBackText(OnBackText onBackText) {
        WXEntryActivity.onBackText = onBackText;
    }

    /**
     * 获取数据回调
     */
    public interface OnBackText {
        void get(int code, ProUserInfo proUserInfo);
    }

    public interface OnShareCallBack {
        void onShare(int code);
    }


    /**
     * 获取用户信息
     *
     * @param accessToken token
     */
    private void getUserInfo(String accessToken, String openID) {
        String uri = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openID;
        HttpUtils.getInstance().get(uri, null, 123, handler);

    }


    @Override
    public void onReq(BaseReq baseReq) {
        Log.i("result", "分享执行到此-----------" + baseReq.openId);

        switch (baseReq.getType()) {
            case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:

                break;
            case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:

                break;
            default:
                break;
        }


    }

    @Override
    public void onResp(BaseResp baseResp) {

        int errorCode = baseResp.errCode;

        Log.i("result", "分享执行到此--eeeeee---------" + errorCode);

        switch (errorCode) {
            case BaseResp.ErrCode.ERR_OK:

                int shareOrLogin= Share.Companion.getIsLoginOrShare(this);
                if(shareOrLogin==1){

                    if (onShareCallBack != null) {
                        onShareCallBack.onShare(errorCode);
                    }
                }else if(shareOrLogin==2){

                    // 用户同意
                    String code = ((SendAuth.Resp) baseResp).code;

                    if (code != null && !code.equals("")) {
                        getWeiAccessToken(code);
                    }
                }

                break;

            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                // 用户拒绝
                if (onBackText != null) {
                    onBackText.get(BaseResp.ErrCode.ERR_AUTH_DENIED, null);
                }

                finish();

                break;

            case BaseResp.ErrCode.ERR_USER_CANCEL:

                if (onBackText != null) {
                    onBackText.get(BaseResp.ErrCode.ERR_USER_CANCEL, null);
                }

                // 用户取消
                finish();

                break;

            case BaseResp.ErrCode.ERR_COMM:

                finish();

                break;

            case BaseResp.ErrCode.ERR_BAN:

                if (onBackText != null) {
                    onBackText.get(BaseResp.ErrCode.ERR_BAN, null);
                }

                finish();

                break;

        }

    }


    /**
     * 获取 access_token
     *
     * @param code code
     */
    private void getWeiAccessToken(String code) {
        handler = new MyHandler(WXEntryActivity.this);

        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=" + Contact.WEIXIN_ID +
                "&secret=" + Contact.WEIXIN_APPSECRET +
                "&code=" + code +
                "&grant_type=authorization_code";

        Log.i("result", "获取地址====" + url);

        HttpUtils.getInstance().get(url, null, 111, handler);
    }
}
